package org.lsy.tlais.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.lsy.tlais.mapper.EmpExprMapping;
import org.lsy.tlais.mapper.EmpMapping;
import org.lsy.tlais.pojo.Emp;
import org.lsy.tlais.pojo.EmpExpr;
import org.lsy.tlais.pojo.EmpPrame;
import org.lsy.tlais.pojo.PageResult;
import org.lsy.tlais.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

@Service
public class EmpServiceImp implements EmpService {

    @Autowired
    private EmpMapping empMapping;

    @Autowired
    private EmpExprMapping empExprMapping;

    //分页查询
    @Override
    public PageResult<Emp> pageQuery(EmpPrame empPrame) {
        //分页查询-使用MyBatis提供的分页插件,设置分页参数
        PageHelper.startPage(empPrame.getPage(), empPrame.getPageSize());

        Page<Emp> emplist = empMapping.list(empPrame);

        return new PageResult<>(emplist.getTotal(), emplist.getResult());

    }

    //新增员工
    @Transactional(rollbackFor = {Exception.class})//添加员工信息时，出现异常，回滚
    @Override
    public void insert(Emp emp) {
        //添加员工基本信息
        emp.setCreateTime((LocalDateTime.now()));
        emp.setUpdateTime((LocalDateTime.now()));
        empMapping.insert(emp);

        //添加员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            //遍历集合，为每个员工工作经历设置员工id
            for (EmpExpr empExpr : exprList) {
                empExpr.setEmpId(emp.getId());
            }
            empExprMapping.insert(exprList);
        }
    }
}
